#pragma once
#include <functional>
#include "libraw/libraw.h"

class SmartLibraw {
public:
    SmartLibraw() = default;
    ~SmartLibraw() = default;

    int raw2rgb(uint16_t* raw_buf, uint32_t img_w, uint32_t img_h, std::function<void(uint8_t*, uint32_t)> callback) {
        int ret;

        ret = m_proc.open_bayer(
            (unsigned char*)raw_buf, img_w*img_h*2,  // 缓冲区与大小
            img_w, img_h, 0, 0, 0, 0,  // 图像尺寸与边距
            0,  // 过程标志
            LIBRAW_OPENBAYER_RGGB,  // 格式
            0,  // 未使用位数
            0,  // 保留标志
            100  // 黑电平值
        );
        if (ret != LIBRAW_SUCCESS) {
            fprintf(stderr, "Cannot open_bayer: %s\n", libraw_strerror(ret));
            exit(EXIT_FAILURE);
        }

        ret = m_proc.unpack();
        if (ret != LIBRAW_SUCCESS) {
            fprintf(stderr, "Cannot unpack: %s\n", libraw_strerror(ret));
            exit(EXIT_FAILURE);
        }

        m_proc.dcraw_process();
        if (ret != LIBRAW_SUCCESS) {
            fprintf(stderr, "Cannot dcraw_process: %s\n", libraw_strerror(ret));
            exit(EXIT_FAILURE);
        }

        libraw_processed_image_t *image = m_proc.dcraw_make_mem_image(&ret);
        if (!image) {
            fprintf(stderr, "Cannot dcraw_make_mem_image: %s\n", libraw_strerror(ret));
            exit(EXIT_FAILURE);
        }

        printf("dcraw_make_mem_image seccess, image len:%d.\n", image->data_size);
        callback(image->data, image->data_size);

        LibRaw::dcraw_clear_mem(image);
        return 0;
    }

private:
    LibRaw m_proc;
};